#!/usr/bin/env python3
"""
简化的股票信息查看工具
"""

import pandas as pd
import json
import os
from pathlib import Path
from typing import Dict, Any
import sys

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from src.utils.logger import get_logger

def get_stock_summary(symbol: str) -> Dict[str, Any]:
    """获取股票摘要信息"""
    data_file = Path(f'./data/stocks/daily/{symbol}_1d.csv')

    if not data_file.exists():
        return {'symbol': symbol, 'exists': False}

    try:
        df = pd.read_csv(data_file, index_col=0, parse_dates=True)

        if df.empty:
            return {'symbol': symbol, 'exists': True, 'empty': True}

        # 获取基本信息
        summary = {
            'symbol': symbol,
            'exists': True,
            'empty': False,
            'total_records': len(df),
            'date_range': {
                'start': df.index.min().strftime('%Y-%m-%d'),
                'end': df.index.max().strftime('%Y-%m-%d')
            },
            'latest_data': {
                'date': df.index.max().strftime('%Y-%m-%d'),
                'open': float(df.iloc[-1]['Open']),
                'high': float(df.iloc[-1]['High']),
                'low': float(df.iloc[-1]['Low']),
                'close': float(df.iloc[-1]['Close']),
                'volume': int(df.iloc[-1]['Volume'])
            }
        }

        # 计算统计信息
        summary['stats'] = {
            'avg_volume': int(df['Volume'].mean()),
            'max_volume': int(df['Volume'].max()),
            'min_price': float(df['Low'].min()),
            'max_price': float(df['High'].max()),
            'price_change': float(df.iloc[-1]['Close']) - float(df.iloc[0]['Open']),
            'price_change_pct': ((float(df.iloc[-1]['Close']) - float(df.iloc[0]['Open'])) / float(df.iloc[0]['Open']) * 100)
        }

        return summary

    except Exception as e:
        return {'symbol': symbol, 'exists': True, 'error': str(e)}

def display_stock_summary(symbol: str):
    """显示股票摘要"""
    summary = get_stock_summary(symbol)

    print(f"\n{'='*60}")
    print(f"股票代码: {summary['symbol']}")
    print(f"{'='*60}")

    if not summary['exists']:
        print("未找到数据")
        return

    if summary.get('empty'):
        print("数据文件为空")
        return

    if 'error' in summary:
        print(f"数据读取错误: {summary['error']}")
        return

    print(f"数据记录: {summary['total_records']:,} 条")
    print(f"数据范围: {summary['date_range']['start']} ~ {summary['date_range']['end']}")

    latest = summary['latest_data']
    print(f"\n最新数据 ({latest['date']}):")
    print(f"   开盘: {latest['open']:.2f}")
    print(f"   最高: {latest['high']:.2f}")
    print(f"   最低: {latest['low']:.2f}")
    print(f"   收盘: {latest['close']:.2f}")
    print(f"   成交量: {latest['volume']:,}")

    stats = summary['stats']
    print(f"\n统计信息:")
    print(f"   平均成交量: {stats['avg_volume']:,}")
    print(f"   最大成交量: {stats['max_volume']:,}")
    print(f"   期间最高: {stats['max_price']:.2f}")
    print(f"   期间最低: {stats['min_price']:.2f}")
    print(f"   总涨跌幅: {stats['price_change_pct']:+.2f}%")

def list_all_stocks_simple():
    """简单列出所有股票"""
    data_dir = Path('./data/stocks/daily')

    if not data_dir.exists():
        print("数据目录不存在")
        return

    files = list(data_dir.glob('*_1d.csv'))
    if not files:
        print("没有找到股票数据文件")
        return

    print(f"\n已存储的股票数据 ({len(files)} 只):")
    print("-" * 70)
    print(f"{'代码':<10} {'记录数':<10} {'最新日期':<12} {'收盘价':<10} {'状态':<8}")
    print("-" * 70)

    for file_path in sorted(files):
        symbol = file_path.stem.replace('_1d', '')
        summary = get_stock_summary(symbol)

        if summary['exists'] and not summary.get('empty'):
            latest_price = summary['latest_data']['close']
            latest_date = summary['latest_data']['date']
            record_count = summary['total_records']

            # 检查数据是否最新（最近3天内）
            from datetime import datetime, timedelta
            latest_dt = datetime.strptime(latest_date, '%Y-%m-%d')
            days_ago = (datetime.now() - latest_dt).days

            if days_ago <= 3:
                status = "最新"
            elif days_ago <= 7:
                status = "较新"
            else:
                status = "过时"

            print(f"{symbol:<10} {record_count:<10,} {latest_date:<12} {latest_price:<10.2f} {status:<8}")
        else:
            print(f"{symbol:<10} {'N/A':<10} {'N/A':<12} {'N/A':<10} {'错误':<8}")

def main():
    """主函数"""
    import argparse

    parser = argparse.ArgumentParser(description='股票信息查看工具')
    parser.add_argument('symbol', nargs='?', help='股票代码（如 000001）')
    parser.add_argument('--list', action='store_true', help='列出所有股票')
    parser.add_argument('--recent', type=int, default=5, help='显示最近几条数据（默认5条）')

    args = parser.parse_args()

    if args.list:
        list_all_stocks_simple()
    elif args.symbol:
        display_stock_summary(args.symbol)

        # 显示最近几条数据
        data_file = Path(f'./data/stocks/daily/{args.symbol}_1d.csv')
        if data_file.exists():
            try:
                df = pd.read_csv(data_file, index_col=0, parse_dates=True)
                if not df.empty:
                    print(f"\n最近 {args.recent} 条数据:")
                    print("-" * 70)
                    recent_data = df.tail(args.recent)
                    print(recent_data.to_string())
            except Exception as e:
                print(f"获取详细数据失败: {e}")
    else:
        print("请指定股票代码或使用 --list 列出所有股票")
        print("示例:")
        print("  python stock_info.py 000001")
        print("  python stock_info.py --list")
        print("  python stock_info.py 000001 --recent 10")

if __name__ == "__main__":
    main()